/**
 * 
 */
package com.cqan.manager;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.Session;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.session.StandardSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqan.session.MemcachedSession;

/**
 * @Description TODO
 * @author wuhui
 * @date 2012-5-25下午3:39:03
 * 
 */
public class MemcachedManager extends StandardManager {

	private static Logger logger = LoggerFactory
			.getLogger(MemcachedSession.class);

	private String perfix = "CQAN_MEMCACHED_";

	private MemcachedClient client;

	private String serverlist;

	private int exp = 30 * 60;

	private transient int timeout = 10;

	private String flag = "true";

	public MemcachedManager() {
		super();
	}

	public Session findSession(String id) throws IOException {
		Session session = super.findSession(id);
		if (session == null && id != null) {
			try {
				Object sid = client.get(this.getPerfix() + id, timeout);
				if (sid != null) {
					session = createSession(id);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return session;
	}

	public Session createSession(String sessionId) {
		Session session = super.createSession(sessionId);
		try {
			client.set(this.getPerfix() + session.getId(), timeout, flag);
		} catch (TimeoutException e) {
			logger.error("createSession error " + e.getMessage());
		} catch (InterruptedException e) {
			logger.error("createSession error " + e.getMessage());
		} catch (MemcachedException e) {
			logger.error("createSession error " + e.getMessage());
		}
		return session;
	}

	@Override
	public StandardSession getNewSession() {

		return new MemcachedSession(this, client, exp);
	}

	public String getPerfix() {
		return perfix;
	}

	public void setPerfix(String perfix) {
		this.perfix = perfix;
	}

	@Override
	public void start() throws LifecycleException {
		this.setPathname("");
		super.start();
		if (serverlist == null || "".equals(serverlist)) {
			throw new IllegalArgumentException("serverlist is null ");
		}
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses(serverlist));
		try {
			if (builder != null) {
				builder.setSessionLocator(new KetamaMemcachedSessionLocator());
				builder.setCommandFactory(new BinaryCommandFactory());
				client = builder.build();
			}
		} catch (IOException e) {
			logger.error("builder client error " + e.getMessage());
		}
	}

	@Override
	public void stop() throws LifecycleException {
		super.stop();
		if (client != null && !client.isShutdown()) {
			try {
				client.shutdown();
			} catch (IOException e) {
				logger.error("stop client error " + e.getMessage());
			}
		}
	}

	@Override
	protected String generateSessionId() {
		if (this.getJvmRoute() != null) {
			return getUUID() + '.' + this.getJvmRoute();
		}
		return getUUID();
	}
	
	private String getUUID(){
		
		return UUID.randomUUID().toString().replace("-", "");
	}

	public String getServerlist() {
		return serverlist;
	}

	public void setServerlist(String serverlist) {
		this.serverlist = serverlist;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

}
